package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	. "web_api_gin/controller"
	"web_api_gin/core"
	"web_api_gin/dao"
	"web_api_gin/dto"
	"web_api_gin/entity"
	"web_api_gin/service"
)

var SysPermissionApi = SysPermissionController{}

type SysPermissionController struct {
}

// 首页接口
func (c *SysPermissionController) Index(ctx *gin.Context) {
	var searchParams dto.SysPermissionGetListReq
	if err := ctx.ShouldBind(&searchParams); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, core.ValidatorTranslateError(err))
		return
	}
	//菜单列表
	menuList, err := dao.SysPermission.GetPermList(ctx, &searchParams)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusExpectationFailed, err.Error())
		return
	}
	var permTreeList []*dto.SysPermissionTree
	if searchParams.Name == "" && searchParams.DisplayName == "" {
		permTreeOriginList := ([]*dto.SysPermissionTree)(nil)
		for _, permission := range menuList {
			permTreeOriginList = append(permTreeOriginList, &dto.SysPermissionTree{
				SysPermission: *permission,
			})
		}
		permTreeList = service.SysPermission.BuildTree(permTreeOriginList)
	} else {
		for _, permission := range menuList {
			permTreeList = append(permTreeList, &dto.SysPermissionTree{
				SysPermission: *permission,
			})
		}
	}
	Success(ctx, gin.H{
		"permList": permTreeList,
	})
}

//保存权限数据
func (c *SysPermissionController) Save(ctx *gin.Context) {
	var form *entity.SysPermission
	if err := ctx.ShouldBind(&form); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, core.ValidatorTranslateError(err))
		return
	}
	//设置表单数据，方便保存日志
	ctx.Set("formData", form)
	rows, err := dao.SysPermission.SavePerm(ctx, form)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, err.Error())
		return
	}
	Success(ctx, gin.H{
		"rows": rows,
	})
}

//菜单删除
func (c *SysPermissionController) Destroy(ctx *gin.Context) {
	var form *dto.SysPermissionFormDestroy
	if err := ctx.ShouldBind(&form); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, core.ValidatorTranslateError(err))
		return
	}
	//设置表单数据，方便保存日志
	ctx.Set("formData", form)
	rows, err := dao.SysPermission.DelPerm(ctx, form.PermIds)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, err.Error())
		return
	}
	Success(ctx, gin.H{
		"rows": rows,
	})
}

// 设置排序
func (c *SysPermissionController) SetOrder(ctx *gin.Context) {
	var form *dto.SysPermissionSetOrderRequest
	if err := ctx.ShouldBind(&form); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, core.ValidatorTranslateError(err))
		return
	}
	//设置表单数据，方便保存日志
	ctx.Set("formData", form)
	err := dao.SysPermission.SetOrder(ctx, form)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, err.Error())
		return
	}
	Success(ctx, gin.H{
		"form": form,
	})
}
